package com.chao.demo.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SmUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.UUID;

public class BoSiAPIController {

    public static void main(String[] args) {
        // headers中的参数
        HttpHeaders header = new HttpHeaders();
        header.set("X-AppId", "3772448343637114882");
        header.set("X-TaxPayerNo", "91500119MAABR79U4Q");
        header.setContentType(MediaType.APPLICATION_JSON);

        // data接口参数
        HashMap<String, Object> param = new HashMap<>(16);
        param.put("serialNumber", "001");
        param.put("nsrsbh", "91500119MAABR79U4Q");
        String data = Base64.encode(JSONUtil.toJsonStr(param));
        System.out.println("data = " + data);

        // 请求参数拼接
        String uuid = UUID.randomUUID().toString();
        System.out.println("uuid = " + uuid);

        String version = "1.0";
        String stringA = "appid=" + "3772448343637114882" + "&data=" + data + "&noise=" + uuid;
        String stringSignTemp = stringA + "&key=" + "91500119MAABR79U4Q" + "&version=" + version;
        System.out.println("stringSignTemp = " + stringSignTemp);

        String sign = SmUtil.sm3(stringSignTemp).toUpperCase();
        System.out.println("sign = " + sign);

        // 接口参数
        HashMap<String, String> busMap = new LinkedHashMap<>();
        busMap.put("data", data);
        busMap.put("noise", uuid);
        busMap.put("version", "1.0");
        busMap.put("sign", sign);

        // 请求地址
        // String url = "http://58.22.61.222:28080/api/standard/v1/rpa/112101002";
        String url = "http://loaclhost:8080/api/standard/v1/112101002";

        // 博思API请求
        HttpEntity<String> httpEntity = new HttpEntity<>(JSONUtil.toJsonStr(busMap), header);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);

        // 请求返回处理
        System.out.println("responseEntity = " + JSONUtil.parseObj(responseEntity.getBody()));
        String str = Base64.decodeStr(JSONUtil.parseObj(responseEntity.getBody()).get("data").toString());
        if (!str.equals("S0000")) {
            System.out.println(Base64.decodeStr(JSONUtil.parseObj(str).get("message").toString()));
        }
        System.out.println("解析消息 = " + Base64.decodeStr(JSONUtil.parseObj(str).get("message").toString()));
        // 调用成功保存接口
        System.out.println(Base64.decodeStr(JSONUtil.parseObj(str).get("message").toString()));
    }
}
